<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库编号/名称查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库专员" prop="staffId">
        <el-input
          v-model="queryParams.staffId"
          placeholder="请输入仓库专员名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.erp_warehouse_type" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>

      <!--      <el-form-item label="创建时间" prop="createdAt">-->
      <!--        <el-date-picker-->
      <!--          v-model="dateRange"-->
      <!--          style="width: 240px"-->
      <!--          value-format="yyyy-MM-dd"-->
      <!--          type="daterange"-->
      <!--          range-separator="-"-->
      <!--          start-placeholder="开始日期"-->
      <!--          end-placeholder="结束日期"-->
      <!--        ></el-date-picker>-->
      <!--      </el-form-item>-->

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:notice:add']"
          >新增
          </el-button>
<!--          <el-button-->
<!--            type="info"-->
<!--            plain-->
<!--            icon="el-icon-upload2"-->
<!--            size="mini"-->
<!--            @click="handleImport"-->
<!--          >导入-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="el-icon-download"-->
<!--            size="mini"-->
<!--            @click="handleExport"-->
<!--            v-hasPermi="['system:role:export']"-->
<!--          >导出-->
<!--          </el-button>-->
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-row>

    <el-table v-loading="loading" :data="warehouseList" @selection-change="handleSelectionChange">
      <el-table-column label="仓库ID" align="center" prop="warehouseId"/>
      <el-table-column label="仓库名称" align="center" prop="warehouseName"/>
      <el-table-column label="仓库专员" align="center" prop="staffId"/>
      <el-table-column label="联系电话" align="center" prop="contactPhone"/>
      <el-table-column label="地址" align="center" prop="address" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="isActive">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_warehouse_type" :value="scope.row.isActive"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:warehouse:edit']"
          >修改
          </el-button>
          <el-button
            v-if="scope.row.isActive === 1"
            size="mini"
            type="warning"
            plain
            icon="el-icon-edit"
            @click="handleUpdateStatus(scope.row)"
            v-hasPermi="['system:warehouse:remove']"
          >禁用
          </el-button>
          <el-button
            v-else
            size="mini"
            type="primary"
            plain
            icon="el-icon-edit"
            @click="handleUpdateStatus(scope.row)"
            v-hasPermi="['system:warehouse:remove']"
          >启用
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库信息对话框 -->
    <el-dialog :title="title" :visible.sync="importDialog" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称"/>
        </el-form-item>
        <el-form-item label="仓库专员" prop="staffId">
          <el-input v-model="form.staffId" placeholder="请输入仓库专员"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入弹窗 -->
    <el-dialog title="导入" :visible.sync="importDialog" width="450px">
      <!--上传组件-->
      <el-upload
        class="upload-demo"
        drag
        action=""
        :file-list="fileList"
        :before-upload="beforeUpload"
        :http-request="uploadExcelFun"
        :on-change="handleChange"
      >
        <i class="el-icon-upload"></i>

        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialog = false">取 消</el-button>

        <el-button type="primary" @click="">确 定</el-button>

      </div>

    </el-dialog>

  </div>
</template>

<script>
import {addWarehouse, getWarehouse, listWarehouse, updateWarehouse, uploadExcel, exportExcel} from "@/api/erp/warehouse"
import {blobValidate} from "@/utils/ruoyi";
import errorCode from "@/utils/errorCode";
import {Message} from "element-ui";
import { saveAs } from 'file-saver'

export default {
  name: "",
  dicts: ['erp_warehouse_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseName: undefined,
        staffId: undefined,
        status: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表数据
      warehouseList: [],
      // 表单参数
      form: {},
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单校验
      rules: {
        warehouseName: [
          {required: true, message: "仓库名称不能为空", trigger: "blur"}
        ],
        staffId: [
          {required: true, message: "仓库专员不能为空", trigger: "blur"}
        ],
        contactPhone: [
          {required: true, message: "联系电话不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "地址不能为空", trigger: "blur"}
        ]


      },
      importDialog: false,
      file: null,
      fileList: []


    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询仓库列表 */
    getList() {
      this.loading = true
      listWarehouse(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        console.log(2222, res)
        this.warehouseList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    // 提交查询

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置查询
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 新增
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加仓库信息"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.warehouseId != null) {
            updateWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            this.form.isActive = 1
            addWarehouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        warehouseName: null,
        staffId: null,
        contactPhone: null,
        address: null,
        createdAt: null,
      }
      this.resetForm("form")
    },
    handleSelectionChange() {

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const warehouseId = row.warehouseId
      getWarehouse(warehouseId).then(response => {
        console.log(1111, response)
        this.form = response.data
        this.open = true
        this.title = "修改仓库信息"
      })
    },
    handleUpdateStatus(row) {
      var status = row.isActive
      var msg1 = status === 1 ? "是否禁用该仓库" : "是否启用该仓库"
      var msg2 = status === 1 ? "禁用仓库" : "启用仓库"

      this.$confirm(msg1, msg2, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.isActive = row.isActive === 1 ? 2 : 1
        updateWarehouse(row).then(response => {
          if (status === 1) {
            this.$modal.msgWarning("禁用成功")
          } else {
            this.$modal.msgSuccess("启用成功")
          }

          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消修改'
        });
      });

    },
    /** 导入按钮操作 */
    handleImport() {
      this.importDialog = true
    },
    /** 上传前的回调，用于清空上次上传的文件列表 */
    beforeUpload(file) {
      console.log('开始上传，清空上次的文件列表');
      this.fileList = []; // 清空文件列表
      return true;
    },
    /** */
    uploadExcelFun() {
      const file = this.file;
      // FormData是js对象,用于存储表单数据
      const formData = new FormData();
      formData.append("file", file); // 由后端接口决定,后端参数叫file
      // 封装的上传文件方法
      uploadExcel(formData).then((res) => {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        // 上传成功后添加到文件列表
        this.fileList.push({
          name: file.name,
        }); // 上传成功后添加到文件列表
        this.importDialog = false; // 关闭弹窗
        this.pageNum = 1; // 刷新列表
        this.getList(); // 刷新列表
      });
    },
    /** 监听文件改变 */
    handleChange(file) {
      console.log("file", file)
      this.file = file.raw;
    },
    /** 导出按钮操作 */
    /** 导出按钮操作 */
    handleExport() {
      exportExcel().then(async (data) => {
        const isBlob = blobValidate(data)
        if (isBlob) {
          const blob = new Blob([data])
          saveAs(blob, "仓库信息_"+new Date().getTime()+".xlsx")
        } else {
          const resText = await data.text()
          const rspObj = JSON.parse(resText)
          const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
          Message.error(errMsg)
        }
      }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
